import React, {useEffect, useMemo} from 'react';
import {useForm} from 'react-hook-form';
import {zodResolver} from '@hookform/resolvers/zod';
import {z} from 'zod';
import {cn, getEffectiveTextLength, TITLE_MAX_EFFECTIVE, URL_MAX_LENGTH} from '@/lib/utils';

export interface EditTabFormValues {
    title: string;
    url: string;
}

interface EditTabFormProps {
    initialData: EditTabFormValues;
    onSubmit: (data: EditTabFormValues) => Promise<void>;
    loading?: boolean;
    formId?: string;
}

const editTabSchema = z.object({
    title: z.preprocess(
        (value) => (typeof value === 'string' ? value.trim() : value),
        z.string().min(1, '标题不能为空').max(200, '标题过长')
    ),
    url: z.preprocess(
        (value) => (typeof value === 'string' ? value.trim() : value),
        z.string().min(1, '链接不能为空').url('请输入有效的网址')
    ),
});

export const EditTabForm: React.FC<EditTabFormProps> = ({
    initialData,
    onSubmit,
    loading = false,
    formId = 'edit-tab-form',
}) => {
    const {
        register,
        handleSubmit,
        formState: {errors},
        watch,
        reset,
        setFocus,
    } = useForm<EditTabFormValues>({
        resolver: zodResolver(editTabSchema),
        defaultValues: initialData,
        mode: 'onChange',
    });

    useEffect(() => {
        setFocus('title');
    }, [setFocus]);

    const titleVal = watch('title');
    const urlVal = watch('url');

    const titleLen = useMemo(() => getEffectiveTextLength(titleVal ?? ''), [titleVal]);
    const urlLen = useMemo(() => (urlVal ?? '').length, [urlVal]);

    const handleFormSubmit = async (values: EditTabFormValues) => {
        await onSubmit({
            title: values.title.trim(),
            url: values.url.trim(),
        });
    };

    return (
        <form
            id={formId}
            onSubmit={handleSubmit(handleFormSubmit)}
            onReset={(e) => {
                e.preventDefault();
                reset();
            }}
            className="space-y-6"
        >
            <div className="space-y-4 px-1">
                <div className="space-y-2">
                    <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                        标题 <span className="text-danger-500">*</span>
                    </label>
                    <input
                        id="title"
                        type="text"
                        placeholder="请输入标签页标题"
                        className={cn(
                            'input',
                            errors.title && 'border-danger-500 focus:border-danger-500 focus:ring-danger-500'
                        )}
                        {...register('title')}
                        disabled={loading}
                    />
                    <p className={cn('text-xs', titleLen > TITLE_MAX_EFFECTIVE ? 'text-red-600' : 'text-gray-400')}>
                        {titleLen} / {TITLE_MAX_EFFECTIVE}
                        {titleLen > TITLE_MAX_EFFECTIVE && ' · 标题过长'}
                    </p>
                </div>

                <div className="space-y-2">
                    <label htmlFor="url" className="block text-sm font-medium text-gray-700">
                        链接地址 <span className="text-danger-500">*</span>
                    </label>
                    <textarea
                        id="url"
                        placeholder="https://example.com"
                        className={cn(
                            'input min-h-24 max-h-52 resize-vertical',
                            errors.url && 'border-danger-500 focus:border-danger-500 focus:ring-danger-500'
                        )}
                        {...register('url')}
                        disabled={loading}
                    />
                    <p className={cn('text-xs', urlLen > URL_MAX_LENGTH ? 'text-red-600' : 'text-gray-400')}>
                        {urlLen} / {URL_MAX_LENGTH}
                        {urlLen > URL_MAX_LENGTH && ' · 链接过长'}
                    </p>
                </div>
            </div>
        </form>
    );
};
